package com.ycsj.goldmedalnewconcept.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.ycsj.goldmedalnewconcept.ButtonActivity;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.StartActivity;
import com.ycsj.goldmedalnewconcept.bean.LoginResponse;
import com.ycsj.goldmedalnewconcept.constant.ConfigConstant;
import com.ycsj.goldmedalnewconcept.constant.Constant;
import com.ycsj.goldmedalnewconcept.utils.SPUtil;
import com.ycsj.goldmedalnewconcept.utils.SPUtils;

import java.io.IOException;

import cn.jpush.android.api.JPushInterface;

//登录
public class LoginActivity extends Activity implements OnClickListener {

	private String account;
	private String password;
	private String token1;
	private String token2;
	private String role;
	private String name;
	private String icon;
	private String schoolName;
	private String schoolId;
	private String disableGroup;
	private EditText et_user;
	private EditText et_password;
	private TextView tv_login;
	private TextView tv_register;
	private TextView forget_password;
	private ImageView iv_fengche;
	private String registration_id;
	private Intent intent;
	Handler handler = new MyHandler();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		intent = getIntent();
		// 获取传递过来的角色类型,对应0,1,2,3学生,家长,老师
		role = intent.getStringExtra("role");

		registration_id = SPUtil.getString(this, Constant.JPUSH_ID, "");
		initView();
		initListener();
		initData();

	}

	public void onResume() {
		super.onResume();
	}

	public void onPause() {
		super.onPause();
	}

	private void initView() {
		et_user = (EditText) findViewById(R.id.et_user);
		et_password = (EditText) findViewById(R.id.et_password);
		tv_login = (TextView) findViewById(R.id.tv_login);
		tv_register = (TextView) findViewById(R.id.tv_register);
		forget_password = (TextView) findViewById(R.id.tv_forget_password);
		iv_fengche = (ImageView) findViewById(R.id.iv_fengche);

		if ("2".equals(role) || "3".equals(role)) {
			tv_register.setText("忘记密码");
			forget_password.setVisibility(forget_password.GONE);
		}
	}

	private void initListener() {
		tv_login.setOnClickListener(this);
		tv_register.setOnClickListener(this);
		forget_password.setOnClickListener(this);
	}

	private void initData() {
		Animation am = new RotateAnimation(0f, 720f,
				Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
				0.5f);
		am.setDuration(5000);
		am.setRepeatCount(Integer.MAX_VALUE);
		am.setFillAfter(true);
		iv_fengche.setAnimation(am);
		am.startNow();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {

			
			if(role==null||TextUtils.isEmpty(role)){
				finish();
				
			}else{
			
			Intent intent = new Intent(this, StartActivity.class);
			startActivity(intent);
			finish();
			overridePendingTransition(R.anim.push_up_in, R.anim.push_up_out);
			}
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.tv_login:
			account = et_user.getText().toString().trim();
			password = et_password.getText().toString().trim();
			if (account.equals("") ) {
				Toast.makeText(getBaseContext(), "请输入正确的手机号", 0).show();
				break;
			}
			if (password.equals("")) {
				Toast.makeText(getBaseContext(), "密码不正确", 0).show();
				break;
			}

			if (role == null || role.equals("")) {
				role = "4";
			}
			login(); // 登录
			tv_login.setClickable(false);
			break;

		case R.id.tv_register:

			if (role == null || role.equals("")) {
				role = "4";
			}
			
			if ("2".equals(role) || "3".equals(role)) {
				Intent intent2 = new Intent(this, ForgetPasswordActivity.class);
				intent2.putExtra("role", role);
				startActivity(intent2);

			} else {
				Intent intent1 = new Intent(this, RegisterActivity.class);
				intent1.putExtra("role", role);
				startActivity(intent1);
			}
			break;
		case R.id.tv_forget_password:
			if (role == null || role.equals("")) {
				role = "4";
			}
			Intent intent2 = new Intent(this, ForgetPasswordActivity.class);
			intent2.putExtra("role", role);
			startActivity(intent2);

			break;
		}
	}

	private void login() {


		Log.i("test","registration_id:"+registration_id);
		//判断极光是否初始化成功
		if("".equals(registration_id)){
			registration_id = JPushInterface.getRegistrationID(this);
		}


		OkHttpClient mOkHttpClient = new OkHttpClient();
		// mOkHttpClient.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
		FormEncodingBuilder builder = new FormEncodingBuilder();
		builder.add("type", "2");
		builder.add("c", account);
		builder.add("p", password);
		builder.add("role", role);
		builder.add("platform", "2");
		builder.add("registration_id", registration_id);
		Request request = new Request.Builder()
				// .url("http://pm.moregolden.com/ycsj_platform/AccountMsg")
//				.url("http://118.190.89.38:8088/ycsj_platform/AccountMsg")
				.url(Constant.SERVER_URL + "AccountMsg")
				
				.post(builder.build())
				.build();
		mOkHttpClient.newCall(request).enqueue(new Callback() {

			@Override
			public void onFailure(Request arg0, IOException arg1) {
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						Toast.makeText(getBaseContext(), "网络无响应，请检查网络连接", 0)
								.show();
						tv_login.setClickable(true);
					}
				});
			}

			@Override
			public void onResponse(Response arg0) throws IOException {
				// 解析Json数据，保存登录状态及身份信息

				try {
					Gson gson = new Gson();
					String json = arg0.body().string();
					Log.e("test", "登录" + json);
					LoginResponse fromJson = gson.fromJson(json,
							LoginResponse.class);

					Message message = Message.obtain();
					message.arg1 = 0;
					message.obj = fromJson;
					handler.sendMessage(message);
				} catch (Exception e) {
					// TODO: handle exceptionLog.e("test", "登录"+json);
					Log.e("test", "登录" + e.toString());
				}
			}
		});
	}

	public class MyHandler extends Handler {

	

		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			tv_login.setClickable(true);
			LoginResponse fromJson = (LoginResponse) msg.obj;
			if (fromJson == null) {
				Toast.makeText(getApplicationContext(), "服务器开小差，请重新尝试", 0)
						.show();
				return;
			}

			if ("1".equals(fromJson.state)) {
				if ("successful".equals(fromJson.result)) {
					token1 = fromJson.token1;
					token2 = fromJson.token2;
					name = fromJson.name;
					icon = fromJson.icon;
					schoolName = fromJson.schoolName;
					schoolId = fromJson.schoolId;
					disableGroup = fromJson.disableGroup;
					if(disableGroup==null||TextUtils.isEmpty(disableGroup)){
						disableGroup = "1";
					}
					
					SPUtil.putString(getApplicationContext(), "account",
							account);
					SPUtil.putString(getApplicationContext(), "token1", token1);
					SPUtil.putString(getApplicationContext(), "token2", token2);
					SPUtil.putString(getApplicationContext(), "name", name);
					SPUtil.putString(getApplicationContext(), "icon", icon);
					SPUtil.putString(getApplicationContext(), "role", role);
					SPUtil.putString(getApplicationContext(), "username",
							account);
					SPUtil.putString(getApplicationContext(), "schoolName",
							schoolName);
					SPUtil.putString(getApplicationContext(), "schoolId",
							schoolId);
					SPUtil.putString(getApplicationContext(), "disableGroup",
							disableGroup);
					SPUtils.put(getApplicationContext(),
							ConfigConstant.IS_LOGIN_ON, true);
					SPUtils.put(getApplicationContext(),
							ConfigConstant.USERTOKEN, token2);
					Toast.makeText(getApplicationContext(), "登录成功，欢迎您", 0)
							.show();

					Intent intent = new Intent(getBaseContext(),
							ButtonActivity.class);
					startActivity(intent);
					finish();

				}
			} else {
				if ("Account wrong".equals(fromJson.result)) {
					Toast.makeText(getApplicationContext(), "账号尚未注册，请检查后重新登录",
							0).show();
				} else if ("Password wrong".equals(fromJson.result)) {
					Toast.makeText(getApplicationContext(), "密码错误，请检查后重新登录", 0)
							.show();
				}
				et_password.setText("");
			}
		}
	}
}







